import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/authStore'
import { ElMessage } from 'element-plus'

export function useLogin() {
  const router = useRouter()
  const authStore = useAuthStore()
  const loading = ref(false)
  const form = reactive({
    username: '',
    password: '',
  })

  const handleLogin = async () => {
    if (!form.username || !form.password) {
      ElMessage.warning('请输入用户名和密码')
      return
    }
    loading.value = true
    try {
      await authStore.login(form)
      ElMessage.success('登录成功！')
    } catch (error) {
      ElMessage.error('用户名或密码错误！')
    } finally {
      loading.value = false
    }
  }

  const goToRegister = () => {
    router.push('/register')
  }

  const goToResetPage = () => {
    router.push('/find-account')
  }

  return {
    form,
    loading,
    handleLogin,
    goToRegister,
    goToResetPage,
  }
}
